/*
 * Created by JFormDesigner on Sat Jul 17 22:40:59 CST 2021
 */

package com.minelx.statementplus.ui.form.ui;

import com.intellij.uiDesigner.core.GridConstraints;
import com.intellij.uiDesigner.core.GridLayoutManager;
import com.minelx.landisk.filesystem.core.File;
import com.minelx.statementplus.ui.form.swing.DialogInputs;
import com.minelx.statementplus.ui.form.swing.OnClosingDialog;
import com.minelx.statementplus.ui.form.ui.memberbased.ProxySettingDialog;
import com.minelx.statementsplus.MajorSql;
import com.minelx.statementsplus.MajorSqlHead;
import com.minelx.statementsplus.Majors;
import com.minelx.statementsplus.split.StringArraySplitter;
import com.minelx.table.core.Table;
import com.minelx.table.core.Tables;

import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.stream.Collectors;

import static com.minelx.statementplus.ui.form.swing.DialogInputs.candyOrJoke;
import static java.nio.charset.StandardCharsets.UTF_8;
import static java.util.stream.Collectors.joining;

/**
 * @author aaa
 */
public class AddingTableDialog extends OnClosingDialog {

	private final DownloadService downloadService;

	private final DefaultListModel<File> tableModel;

	public AddingTableDialog(Window owner,
	                         DownloadService downloadService,
	                         DefaultListModel<File> tableModel) {
		super(owner, e -> {
		});
		this.tableModel = tableModel;
		initComponents();

		this.downloadService = downloadService;
	}

	private void wholeProxyButtonActionPerformed(ActionEvent e) {
		downloadService.buildAndDownloadWithWholeProxy(this);
	}

	// FIXME: 2021/8/24  NEEDED REFACTORING !!!
	private void memberBasedProxyButtonActionPerformed(ActionEvent e) {
		new ProxySettingDialog(
				this,
				proxyIds -> downloadService.buildAndDownload(this, Majors.proxies(proxyIds))
		).setVisible(true);
	}

	private void memberBasedMemberIdButtonActionPerformed(ActionEvent e) {
		MajorSql major = Majors.memberIds(preprocessMemberIds(candyOrJoke("输入商户号: ")));
		downloadService.buildAndDownload(this, major);
	}

	private void quoteMemberIdButtonActionPerformed(ActionEvent e) {
		File file = (File) DialogInputs.chooseOneOf(this, tableModel.toArray(), "选择文件");
		try {
			Table table = Tables.csv(file.read(UTF_8));
			String[] title = table.form().title().stream().toArray(String[]::new);
			String selectedColumn = DialogInputs.chooseOneOf(this, title, "选择列");
			MajorSql major = Majors.memberIds(table.column(selectedColumn).stream().mapToLong(Long::parseLong).toArray());
			downloadService.buildAndDownload(this, major);
		} catch (IOException exception) {
			exception.printStackTrace();
		}
	}

	private void wechatButtonActionPerformed(ActionEvent e) {
		String[] wechatIds = candyOrJoke("输入微信间联号: ").split("\\s|,");
		downloadService.buildAndDownload(this, Majors.wechatIds(wechatIds));
	}

	private void zfbButtonActionPerformed(ActionEvent e) {
		String[] zfbIds = candyOrJoke("输入支付宝间联号: ").split("\\s|,");
		downloadService.buildAndDownload(this, createZfbMajorSql(zfbIds));
	}

	private MajorSql createZfbMajorSql(String[] zfbIds) {
		return new MajorSql() {
			@Override
			public MajorSqlHead head() {
				String asContent = Arrays.stream(zfbIds).map(item -> "\"" + item + "\"").collect(joining(","));
				return new MajorSqlHead("2=> SELECT * FROM (SELECT member_wx_zfb_id, member_id, yc_zfb_bind FROM t_a_member_wx_zfb WHERE member_wx_zfb_id > {{BVAL}} AND yc_zfb_bind IN (" + asContent + "))a ORDER BY a.member_wx_zfb_id LIMIT 1000;", "member_wx_zfb_id", List.of("memberId"));
			}

			@Override
			public List<MajorSql> split() {
				return new StringArraySplitter(zfbIds, partition -> createZfbMajorSql(partition)).split();
			}
		};
	}

	private void quoteWechatIdButtonActionPerformed(ActionEvent e) {
		File file = (File) DialogInputs.chooseOneOf(this, tableModel.toArray(), "选择文件");
		try {
			Table table = Tables.csv(file.read(UTF_8));
			String[] title = table.form().title().stream().toArray(String[]::new);
			String selectedColumn = DialogInputs.chooseOneOf(this, title, "选择列");
			MajorSql major = Majors.wechatIds(selectedColumn.split("\\s|,"));
			downloadService.buildAndDownload(this, major);
		} catch (IOException exception) {
			exception.printStackTrace();
		}
	}

	public static long[] preprocessMemberIds(String memberIdsAsText) {
		// deal with space char
		if (memberIdsAsText.contains(" ")) {
			memberIdsAsText = memberIdsAsText.replace(" ", ",");
		}

		return Arrays.stream(memberIdsAsText.split(","))
				.mapToLong(Long::parseLong)
				.map(item -> {
					if (item > 5000500000L) {
						return item - 5000500000L;
					}
					if (item > 1000500000) {
						return item - 1000500000;
					}
					return item;
				})
				.toArray();
	}

	private void initComponents() {
		// JFormDesigner - Component initialization - DO NOT MODIFY  //GEN-BEGIN:initComponents
		panel1 = new JPanel();
		panel3 = new JPanel();
		label1 = new JLabel();
		panel4 = new JPanel();
		label2 = new JLabel();
		memberBasedMemberIdButton = new JButton();
		memberBasedProxyButton = new JButton();
		wechatButton = new JButton();
		zfbButton = new JButton();
		wholeProxyButton = new JButton();
		panel6 = new JPanel();
		label4 = new JLabel();
		quoteMemberIdButton = new JButton();
		quoteWechatIdButton = new JButton();
		panel5 = new JPanel();
		label3 = new JLabel();
		salesmanAccountButton = new JButton();

		//======== this ========
		setTitle("\u6dfb\u52a0\u65b0\u7684\u8868\u683c");
		setDefaultCloseOperation(WindowConstants.DISPOSE_ON_CLOSE);
		var contentPane = getContentPane();
		contentPane.setLayout(new BorderLayout());

		//======== panel1 ========
		{
			panel1.setBorder(new EmptyBorder(12, 12, 12, 12));
			panel1.setLayout(new BorderLayout());

			//======== panel3 ========
			{
				panel3.setLayout(new GridLayoutManager(5, 1, new Insets(0, 0, 0, 0), 5, -1));

				//---- label1 ----
				label1.setText("\u9009\u62e9\u8d44\u6e90!");
				label1.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 74));
				panel3.add(label1, new GridConstraints(0, 0, 1, 1,
					GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_NONE,
					GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
					GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
					null, null, null));

				//======== panel4 ========
				{
					panel4.setLayout(new FlowLayout(FlowLayout.CENTER, 22, 5));

					//---- label2 ----
					label2.setText("\u8f93\u5165:");
					label2.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 24));
					panel4.add(label2);

					//---- memberBasedMemberIdButton ----
					memberBasedMemberIdButton.setText("100\u5546\u6237\u53f7");
					memberBasedMemberIdButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
					memberBasedMemberIdButton.addActionListener(e -> memberBasedMemberIdButtonActionPerformed(e));
					panel4.add(memberBasedMemberIdButton);

					//---- memberBasedProxyButton ----
					memberBasedProxyButton.setText("\u5730\u5e02");
					memberBasedProxyButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
					memberBasedProxyButton.addActionListener(e -> memberBasedProxyButtonActionPerformed(e));
					panel4.add(memberBasedProxyButton);

					//---- wechatButton ----
					wechatButton.setText("\u5fae\u4fe1\u95f4\u8054");
					wechatButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
					wechatButton.addActionListener(e -> wechatButtonActionPerformed(e));
					panel4.add(wechatButton);

					//---- zfbButton ----
					zfbButton.setText("\u652f\u4ed8\u5b9d\u95f4\u8054");
					zfbButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
					zfbButton.addActionListener(e -> zfbButtonActionPerformed(e));
					panel4.add(zfbButton);

					//---- wholeProxyButton ----
					wholeProxyButton.setText("\u5168\u56fd");
					wholeProxyButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
					wholeProxyButton.addActionListener(e -> wholeProxyButtonActionPerformed(e));
					panel4.add(wholeProxyButton);
				}
				panel3.add(panel4, new GridConstraints(1, 0, 1, 1,
					GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
					GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
					GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
					null, null, null));

				//======== panel6 ========
				{
					panel6.setLayout(new FlowLayout(FlowLayout.CENTER, 22, 5));

					//---- label4 ----
					label4.setText("\u5f15\u7528\u5df2\u6709\u8d44\u6e90:");
					label4.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 24));
					panel6.add(label4);

					//---- quoteMemberIdButton ----
					quoteMemberIdButton.setText("100\u5546\u6237\u53f7");
					quoteMemberIdButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
					quoteMemberIdButton.addActionListener(e -> quoteMemberIdButtonActionPerformed(e));
					panel6.add(quoteMemberIdButton);

					//---- quoteWechatIdButton ----
					quoteWechatIdButton.setText("\u5fae\u4fe1\u95f4\u8054");
					quoteWechatIdButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
					quoteWechatIdButton.addActionListener(e -> quoteWechatIdButtonActionPerformed(e));
					panel6.add(quoteWechatIdButton);
				}
				panel3.add(panel6, new GridConstraints(2, 0, 1, 1,
					GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
					GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
					GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
					null, null, null));

				//======== panel5 ========
				{
					panel5.setLayout(new FlowLayout(FlowLayout.CENTER, 20, 0));

					//---- label3 ----
					label3.setText("\u53ef\u83b7\u5f97\u5ba2\u6237\u7ecf\u7406: ");
					label3.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 24));
					panel5.add(label3);

					//---- salesmanAccountButton ----
					salesmanAccountButton.setText("\u5ba2\u6237\u7ecf\u7406\u8d26\u53f7");
					salesmanAccountButton.setFont(new Font("Microsoft JhengHei Light", Font.PLAIN, 26));
					salesmanAccountButton.addActionListener(e -> memberBasedMemberIdButtonActionPerformed(e));
					panel5.add(salesmanAccountButton);
				}
				panel3.add(panel5, new GridConstraints(3, 0, 1, 1,
					GridConstraints.ANCHOR_CENTER, GridConstraints.FILL_BOTH,
					GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
					GridConstraints.SIZEPOLICY_CAN_SHRINK | GridConstraints.SIZEPOLICY_CAN_GROW,
					null, null, null));
			}
			panel1.add(panel3, BorderLayout.CENTER);
		}
		contentPane.add(panel1, BorderLayout.CENTER);
		setSize(1000, 795);
		setLocationRelativeTo(getOwner());
		// JFormDesigner - End of component initialization  //GEN-END:initComponents
	}

	// JFormDesigner - Variables declaration - DO NOT MODIFY  //GEN-BEGIN:variables
	private JPanel panel1;
	private JPanel panel3;
	private JLabel label1;
	private JPanel panel4;
	private JLabel label2;
	private JButton memberBasedMemberIdButton;
	private JButton memberBasedProxyButton;
	private JButton wechatButton;
	private JButton zfbButton;
	private JButton wholeProxyButton;
	private JPanel panel6;
	private JLabel label4;
	private JButton quoteMemberIdButton;
	private JButton quoteWechatIdButton;
	private JPanel panel5;
	private JLabel label3;
	private JButton salesmanAccountButton;
	// JFormDesigner - End of variables declaration  //GEN-END:variables
}
